package com.farm.common.util;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.experimental.UtilityClass;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@UtilityClass
public class StringRange {

    // 泛型作为入参
    public <T> T dateConverter(String s, Class<T> t, Integer i, String SEPARATOR) {
        if (ObjectUtil.isEmpty(s)) {
            return null;
        }
        if (s.contains(SEPARATOR)) {
            try {
                List<String> sl = Arrays.asList((ObjectUtil.isEmpty(s) ? ("" + SEPARATOR) : s).split(SEPARATOR));
                if (ObjectUtil.isNotEmpty(sl.get(i))) {
                    s = sl.get(i);
                } else {
                    return null;
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                return null;
            }
        }
        if (t == LocalDateTime.class) {
            return t.cast(LocalDateTimeUtil.parse(s));
        }
        if (t == LocalDate.class) {
            return t.cast(LocalDateTimeUtil.parseDate(s));
        }
        return null;
    }

    public <T> T dateConverter(String s, Class<T> t, Integer i) {
        return dateConverter(s, t, i,",");
    }

    public <T> T dateConverter(String s, Class<T> t) {
        return dateConverter(s, t, 0,",");
    }

    public String getOne(String s, Integer i,String SEPARATOR) {
        if (ObjectUtil.isEmpty(s)) {
            return null;
        }
        if (s.contains(SEPARATOR)) {
            try {
                List<String> sl = Arrays.asList((ObjectUtil.isEmpty(s) ? ("" + SEPARATOR) : s).split(SEPARATOR));
                if (ObjectUtil.isNotEmpty(sl.get(i))) {
                    return sl.get(i);
                } else {
                    return null;
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                return null;
            }
        }
        return s;
    }

    public String getOne(String s, Integer i) {
        return getOne(s, i,",");
    }

    public String getOne(String s) {
        return getOne(s, 0,",");
    }

}
